import React, { useState, useEffect } from "react";
import { Layout, Button, Modal, Form, Input, InputNumber, message } from "antd";
import { useStore } from "../../stores/store.jsx";
import { CreatejobApi } from "../../api/recruiter";
import JobSearch from "./search";
import JobList from "./JobList";
import "../../assets/style/App.css";

import "../../assets/style/home.css"; // 引入公共样式

const { Content } = Layout;

const PostJobs = () => {
  const { state, dispatch, getUserInfo } = useStore();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [filteredJobs, setFilteredJobs] = useState([]);

  useEffect(() => {
    const fetchUserInfo = async () => {
      await getUserInfo(); // 获取用户信息
      setFilteredJobs(state.userInfo?.jobs || []); // 初始化职位列表
    };

    fetchUserInfo();
  }, [getUserInfo, state.userInfo]);

  const handleAddJobClick = () => {
    setIsModalVisible(true);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const newJob = await CreatejobApi(values);

      const updatedJobs = [...state.userInfo.jobs, newJob];
      dispatch({
        type: "SET_USER_INFO",
        payload: {
          ...state.userInfo,
          jobs: updatedJobs,
        },
      });

      setFilteredJobs(updatedJobs); // 更新过滤后的职位列表
      setIsModalVisible(false);
      form.resetFields();
      message.success("发布成功");
    } catch (error) {
      console.error("发布职位失败:", error);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const handleSearch = (searchTerm) => {
    const jobs = state.userInfo?.jobs || [];
    if (!searchTerm) {
      setFilteredJobs(jobs); // 恢复原始数据
    } else {
      const filtered = jobs.filter((job) =>
        job.job_name.toLowerCase().includes(searchTerm.toLowerCase())
      );
      setFilteredJobs(filtered);
    }
  };

  const handleJobUpdate = async (updatedJob) => {
    try {
      const updatedJobs = state.userInfo.jobs.map((job) =>
        job.job_id === updatedJob.job_id ? updatedJob : job
      );

      dispatch({
        type: "SET_USER_INFO",
        payload: {
          ...state.userInfo,
          jobs: updatedJobs,
        },
      });

      setFilteredJobs(
        filteredJobs.map((job) =>
          job.job_id === updatedJob.job_id ? updatedJob : job
        )
      );

      message.success("职位信息更新成功");
    } catch (error) {
      console.error("更新职位列表失败:", error);
      message.error("更新职位列表失败");
    }
  };

  return (
    <Layout
      style={{
        maxWidth: "1200px",
        margin: "0 auto",
        height: "89vh", // 父容器高度占满屏幕
        background: "#f5f5f5", // 背景颜色
      }}
    >
      <Content
        style={{
          flex: 3,
          padding: "20px",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            marginBottom: "10px",
          }}
        >
          <Button type="primary" onClick={handleAddJobClick}>
            发布职位
          </Button>
          {/* 搜索组件 */}
          <JobSearch onSearch={handleSearch} filters={filteredJobs} />
        </div>

        {/* 职位列表组件 */}
        <div
          style={{
            marginTop: "20px",
            flex: 1,
            overflowY: "auto", // 启用内部滚动
            paddingRight: "10px", // 防止内容贴边
          }}
          className="scroll-container"
        >
          <JobList jobs={filteredJobs} onJobUpdate={handleJobUpdate} />
        </div>
      </Content>

      {/* 发布职位弹窗 */}
      <Modal
        title="发布职位"
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        okText="发布"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Form.Item
            label="职位名称"
            name="job_name"
            rules={[{ required: true, message: "请输入职位名称" }]}
          >
            <Input placeholder="请输入职位名称" />
          </Form.Item>
          <Form.Item
            label="公司名称"
            name="company"
            rules={[{ required: true, message: "请输入公司名称" }]}
          >
            <Input placeholder="请输入公司名称" />
          </Form.Item>
          <Form.Item
            label="企业规模（员工数）"
            name="company_size"
            rules={[{ required: true, message: "请输入企业规模" }]}
          >
            <InputNumber
              placeholder="请输入企业规模"
              min={1}
              style={{ width: "100%" }}
            />
          </Form.Item>
          <Form.Item
            label="薪资 (k/月)"
            name="salary"
            rules={[{ required: true, message: "请输入薪资" }]}
          >
            <InputNumber
              placeholder="请输入薪资"
              min={0}
              style={{ width: "100%" }}
            />
          </Form.Item>
          <Form.Item
            label="工作详情"
            name="detail"
            rules={[{ required: true, message: "请输入工作详情" }]}
          >
            <Input.TextArea placeholder="请输入工作详情" rows={4} />
          </Form.Item>
          <Form.Item
            label="负责人"
            name="head"
            rules={[{ required: true, message: "请输入负责人姓名" }]}
          >
            <Input placeholder="请输入负责人姓名" />
          </Form.Item>
          <Form.Item
            label="负责人职位"
            name="posts"
            rules={[{ required: true, message: "请输入负责人职位" }]}
          >
            <Input placeholder="请输入负责人职位" />
          </Form.Item>
          <Form.Item
            label="企业地址"
            name="company_address"
            rules={[{ required: true, message: "请输入企业地址" }]}
          >
            <Input placeholder="请输入企业地址" />
          </Form.Item>
          <Form.Item
            label="企业所属行业"
            name="company_industry"
            rules={[{ required: true, message: "请输入企业所属行业" }]}
          >
            <Input placeholder="请输入企业所属行业" />
          </Form.Item>
          <Form.Item
            label="企业邮箱"
            name="company_email"
            rules={[
              { required: true, message: "请输入企业邮箱" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input placeholder="请输入企业邮箱" />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default PostJobs;
